package com.hqyj.hive.udf;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hive.ql.exec.UDF;
import java.util.Calendar;

public class Birthday2Age extends UDF {
    public int evaluate(String birth) {
        if (StringUtils.isEmpty(birth)) return -1;
        //1.输入年月日
        String[] ymd = birth.split("-");
        int year = Integer.parseInt(ymd[0]);
        int month = Integer.parseInt(ymd[1]);
        int day = Integer.parseInt(ymd[2]);
        //2.当前的日期
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        int currentMonth = calendar.get(Calendar.MONTH);
        int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
        //3.计算年龄
        int age = currentYear - year;
        if (currentMonth < month) age = age - 1;
        else if (currentMonth == month && currentDay < day) age = age - 1;
        return age;
    }
}
